package com.tro.common.util.mybatis;

import org.apache.commons.lang.StringEscapeUtils;

public class Condition {
	 private String name;// 条件名
	    private Operator Opertion;// 运算符
	    private Object value;// 条件值
	    private Integer jdbcType;// 1 不要添加引号，2 需要添加引号 3 to_date(yyyy-mm-dd) 4 yyyy-mm-dd hh24:mi:ss

	    public Condition() {
	        super();
	    }

	    public Condition(Operator opertion, String name, Object value,Integer jdbcType) {
	        super();
	        Opertion = opertion;
	        this.name = name;
	        this.jdbcType=jdbcType;
	        this.setValue(value);
	    }

	    public static Condition eq(String propertyName, Object value,Integer jdbcType) {
	        return new Condition(Operator.Equal, propertyName, value,jdbcType);
	    }
	    
	    public static Condition like(String propertyName, Object value,Integer jdbcType) {
	        return new Condition(Operator.Like, propertyName, value,jdbcType);
	    }

	    public String getName() {
	        return name;
	    }

	    public void setName(String name) {
	        this.name = name;
	    }

	    public Operator getOpertion() {
	        return Opertion;
	    }

	    public void setOpertion(Operator opertion) {
	        Opertion = opertion;
	    }

	    public Object getValue() {
	        return value;
	    }

	    public void setValue(Object value) {
	    	if(this.jdbcType==null){
	    		this.value="";
	    		return;
	    	}
	    	value =StringEscapeUtils.escapeSql(value.toString());
	        if (this.Opertion != null && this.Opertion.equals(Operator.Like)) {
	            this.value = "'%" + value + "%'";//必须加引号...
	        } else {
	        	Object finalVal=value; 
	        	if(this.jdbcType==2){
	        		finalVal="'"+finalVal+"'";
	        	}else if(this.jdbcType==3){
	        		if(finalVal.toString().length()>10){
	        			finalVal=finalVal.toString().substring(0,10);
	        		}
	        		finalVal="to_date('"+finalVal+"','yyyy-mm-dd')";
	        	}else if(this.jdbcType==4){
	        		finalVal="to_date('"+finalVal+"','yyyy-mm-dd hh24:mi:ss')";
	        	}
	            this.value = finalVal;
	        }
	    }
	    
	    public String getSql(){
	    	StringBuffer sb = new StringBuffer();
	    	sb.append(this.name);
	    	switch (this.Opertion) {
			case Equal:
				sb.append(" = ");
				break;
			case UnEqual:
				sb.append(" <> ");
				break;
			case GreatThan:
				sb.append(" >= ");
				break;
			case LessThan:
				sb.append(" <= ");
				break;
			case Like:
				sb.append(" like ");
				break;
			}
	    	sb.append(this.value);
	    	return sb.toString();
	    }
	    
	    public static void main(String[] args) {
	    	Condition c=Condition.eq("user_name", "likun", 3);
	    	System.out.println(c.getSql());
		}
}
